import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

/**
 * Class that handles the events from the Journey Planner screen
 * @author Paula Gonz�lez Mu�oz
 * @author Alex Bruck
 * @author Cem Altel
 */
public class TripListener implements CommandListener
{
	/**
 	 * GUI element which events the TripListener is going to handle
 	 */
	GUI m;
	
	/**
 	 * Constructor
 	 * @param m GUI element which events the TripListener is going to handle
 	 */
	public TripListener (GUI m)
	{
		this.m = m;
	}

	/** 
 	 * Method that handles the events from the journey planner screen
 	 * @param c event to handle
 	 * @param d displayable element to interact with
 	 * @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)
 	 */
	public void commandAction(Command c, Displayable d) {
		String label = c.getLabel();
		
		if(label.equals("Calculate"))
		{
			String origin;
			String destination;
			Vector result;
			
			if (m.origin.equals("")||m.destination.equals("")){
				//show some kind of error notice
				//int timeout = Alert.FOREVER;
				//Alert error = new Alert("Origin or destination missing", "Please select origin and destination of your trip", null, AlertType.ERROR );
				//error.setTimeout(timeout);
				
				
				//m.display.setCurrent(error);
				//m.newTravel();
				result = new Vector();
				String path = "Origin or destination missing";
				result.addElement(path);
				m.showResult(result);
				
			}
			else
			{
				//assuming format "name,id" for the strings
				int i = m.origin.indexOf(",");
				origin = m.origin.substring(i+1);
				i = m.destination.indexOf(",");
				destination = m.destination.substring(i+1);
				result = m.mapEngine.findRoute(origin, destination);
				m.showResult(result);
				//here we should launch the computations needed and show the result.	
			}
			
		}
		else if (label.equals("Back"))
		{

			m.mainMenu();
		}
		else
 		{
 			List down = (List)m.display.getCurrent();
 			//depending on the selection we are going to set the origin or the destination for our trip
 			//so we'll have to call the appropiate method
 			switch(down.getSelectedIndex())
 			{
 			case 0:
 				m.setOrigin();
 				break;
 			case 1:
 				m.setDestination();
 				break;
 				
 			}
 		}
 	}
		
}